﻿using Parylene_CVD.DAL;
using Parylene_CVD.Model.DModels;
using Parylene_CVD.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Parylene_CVD.Tools;
using System.IO;

namespace Parylene_CVD.Views
{
    /// <summary>
    /// EditDevice.xaml 的交互逻辑
    /// </summary>
    public partial class EditDevice : Window
    {
        public Device EditedDevice { get; private set; }
        public EditDevice(Device device)
        {
            InitializeComponent();
            EditedDevice = device;
            DataContext = EditedDevice; // 绑定数据上下文
        }

        /// <summary>
        /// 点击保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SaveButton_Click(object sender, RoutedEventArgs e)
        {

            // 清空错误信息
            StringBuilder errors = new StringBuilder();

            // 必填项校验
            if (string.IsNullOrWhiteSpace(EditedDevice.DeviceName))
            {
                errors.AppendLine("设备名不能为空。");
            }

            if (string.IsNullOrWhiteSpace(EditedDevice.IP))
            {
                errors.AppendLine("IP地址不能为空。");
            }
            else
            {
                // IP地址格式校验
                if (!CheckIPAdress.IsValidIPAddress(EditedDevice.IP))
                {
                    errors.AppendLine("IP地址格式无效，请输入正确的IPv4地址（例如：192.168.1.1）。");
                }
            }

            if (string.IsNullOrWhiteSpace(EditedDevice.Port))
            {
                errors.AppendLine("端口号不能为空。");
            }
            else
            {
                // 端口号格式校验
                if (!int.TryParse(EditedDevice.Port, out int portNumber) || portNumber < 1 || portNumber > 65535)
                {
                    errors.AppendLine("端口号无效，请输入介于 1 到 65535 之间的数字。");
                }
            }

            // 如果有错误，抛出异常或显示提示
            if (errors.Length > 0)
            {
                // 显示消息框（需要引用 System.Windows）
                MessageBox.Show(errors.ToString(), "输入错误", MessageBoxButton.OK, MessageBoxImage.Warning);
                DialogResult = false; // 保存失败

            }
            else
            {
                try
                {
                    DeviceDAL deviceDAL = new DeviceDAL();
                    EditedDevice.UpdateTime = DateTime.Now;
                    deviceDAL.UpdataDevice(EditedDevice, "DeviceName,IP,Port,UpdateTime");
                    MakeNewDeviceDir();
                    DialogResult = true; // 确认保存
                }
                catch (Exception ex)
                {
                    if (ex.Message.Contains("UNIQUE KEY", StringComparison.OrdinalIgnoreCase))
                    {
                        MessageBox.Show("保存失败：设备名重复！", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                    else
                    {
                        MessageBox.Show($"保存失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    }

                    DialogResult = false; // 保存失败
                }
            }
            
            Close();
        }

        /// <summary>
        /// 如果修改了设备名新建一个目录保存数据
        /// </summary>
        public void MakeNewDeviceDir()
        {
            ParameterDAL parameterDAL = new ParameterDAL();
            string BasePath = parameterDAL.GetParameter("ParameterName = '数据保存目录'", "")[0].ParameterValue;
            // 拼接新文件夹路径
            string newFolderPath = System.IO.Path.Combine(BasePath, EditedDevice.DeviceName);

            // 检查并创建文件夹
            if (!Directory.Exists(newFolderPath))
            {
                Directory.CreateDirectory(newFolderPath);
            }
        }

        /// <summary>
        /// 点击取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false; // 取消操作
            Close();
        }
    }
}
